package im

import (
	"context"
	"fmt"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	_const "github.com/flipped-aurora/gin-vue-admin/server/global/const"
	"github.com/flipped-aurora/gin-vue-admin/server/model/im/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/im/response"
	http_request "github.com/flipped-aurora/gin-vue-admin/server/utils/request"
	"github.com/pkg/errors"
	"strconv"
	"time"
)

type IMNotificationService struct{}

var IMNotificationServiceApp = new(IMNotificationService)

// SendNotification 发送系统通知
func (i IMNotificationService) SendNotification(ctx context.Context, req request.IMSendNotificationMsgRequest) error {
	var URL = _const.OpenImServerAddress + "/msg/batch_send_msg"

	// 从缓存中获取adminToken
	adminToken, errToken := global.IMAdminTokenCache.Get(ctx)
	if errToken != nil {
		return fmt.Errorf("failed get token cache: %w", errToken)
	}

	var headers = make(map[string]string, 1)
	headers[request.OpenIMOperationIDHeader] = strconv.Itoa(time.Now().Second())
	headers[request.OpenIMTokenHeader] = adminToken.(string)
	var openImResp = response.OpenImResponse{}
	var _, errReq = http_request.HttpRequest(URL, http_request.POST, headers, http_request.EmptyParams, req, &openImResp)

	if errReq != nil {
		fmt.Println(errReq.Error())
		return errReq
	}

	if openImResp.ErrCode != 0 {
		return errors.Errorf("unexpected openim code %s, err_dlt: %s",
			openImResp.ErrCode, openImResp.ErrDlt)
	}

	return nil
}
